package cn.caplike.demo.nio._2021.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Objects;

/**
 * Description:
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2021-12-24 12:54
 */
@SuppressWarnings("DuplicatedCode")
public class NioFileCopy {

    public static void main(String[] args) throws Throwable{
        FileInputStream inputStream = new FileInputStream(Objects.requireNonNull(NioFromIo.class.getResource("/data/nio-from-io-read.txt")).getPath());
        FileOutputStream outputStream = new FileOutputStream(Objects.requireNonNull(NioFromIo.class.getResource("/data/nio-from-io-write.txt")).getPath());

        final FileChannel inputChannel = inputStream.getChannel();
        final FileChannel outputChannel = outputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        while (true) {
            buffer.clear(); // 如果注释掉这一行?
            // 实际读到的字节个数
            int read = inputChannel.read(buffer);
            System.out.println("read: " + read);
            if (-1 == read) {
                break;
            }

            buffer.flip();
            outputChannel.write(buffer);
        }

        inputChannel.close();
        outputChannel.close();
    }
}
